package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.IUserSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserSevice iUserSevice;


	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {

        IPage<User> userPage = new Page<>(currentPage,pageSize);
        IPage<User> page = iUserSevice.page(userPage);
        List<User> records = page.getRecords();
        long total = page.getTotal();
        PageBean<User> userPageBean = new PageBean<>(records,total);
        if (records!=null){
            return new Result(Code.GET_OK,userPageBean,"查询成功!");

        }
        return new Result(Code.GET_ERR,null,"查询失败!");
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        if (iUserSevice.save(user)){
            return new Result(Code.SAVE_OK,null,"添加成功!");
        }
        return new Result(Code.SAVE_ERR,null,"添加失败!");
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        if (iUserSevice.removeById(id)){
            return new Result(Code.DELETE_OK,null,"删除成功!");
        }
        return new Result(Code.DELETE_ERR,null,"删除失败!");
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId,user.getId());
        if (iUserSevice.update(user,lqw)){
            return new Result(Code.UPDATE_OK,null,"修改成功!");
        }
        return new Result(Code.UPDATE_ERR,null,"修改失败!");
    }

}
